package com.telenav.meishi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class FoodMenuActivity extends Activity {
	String[] titles = new String[] {};
	Bitmap[] images = new Bitmap[] {};
	String[] foods = new String[] {};
	ArrayList<String> searchArray = new ArrayList<String>();
	GridView gridView = null;
	int pageCount = 0;
	int pageSize = 40;
	int currentPageId = 1;
	static final int LOADTYPE_FILE = 1;
	static final int LOADTYPE_KEY = 2;
	int loadType = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_foodmenu);

		try {
			String menuFile = getIntent().getStringExtra("menuFile");
			String searchKey = getIntent().getStringExtra("searchKey");
			if (menuFile != null && !menuFile.equals("")) {
				InputStream is = this.getAssets().open(menuFile);
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = br.readLine();
				foods = line.split("\\|\\|");
				pageCount = foods.length / pageSize + (foods.length % pageSize == 0 ? 0 : 1);

				currentPageId = 1;
				loadType = LOADTYPE_FILE;
				loadPage(currentPageId);
			} else if (searchKey != null && !searchKey.equals("")) {
				Iterator<String> it = Util.getFoodMap().keySet().iterator();
				while (it.hasNext()) {
					String value = it.next();
					if (value.contains(searchKey)) {
						searchArray.add(value);
					}
				}
				pageCount = searchArray.size() / pageSize + (searchArray.size() % pageSize == 0 ? 0 : 1);
				currentPageId = 1;
				loadType = LOADTYPE_KEY;
				loadPage(currentPageId);
			}

			gridView = (GridView) findViewById(R.id.gridView_food);
			gridView.setColumnWidth(180);
			gridView.setAdapter(new ImageAdapter(this));
			gridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					String title = titles[position];
					Intent intent = new Intent(FoodMenuActivity.this, FoodViewActivity.class);
					intent.putExtra("title", title);
					startActivity(intent);
				}
			});

			Button button_prev = (Button) findViewById(R.id.button_prev);
			Button button_next = (Button) findViewById(R.id.button_next);
			button_prev.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (currentPageId > 1) {
						currentPageId--;
						try {
							loadPage(currentPageId);
							gridView.invalidateViews();
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(FoodMenuActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
						}
					}

				}
			});
			button_next.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (currentPageId < pageCount) {
						currentPageId++;
						try {
							loadPage(currentPageId);
							gridView.invalidateViews();
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(FoodMenuActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
						}
					}

				}
			});
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	private void loadPage(int pageId) throws Exception {
		if (loadType == LOADTYPE_FILE) {
			TextView textView1 = (TextView) findViewById(R.id.textView1);
			textView1.setText(pageId + "/" + pageCount);
			int leftCount = foods.length - ((pageId - 1) * pageSize);
			int pageCount = leftCount > (pageSize-1)?pageSize:leftCount;
			titles = new String[pageCount];
			images = new Bitmap[pageCount];
			for (int i = 0; i < pageCount; i++) {
				titles[i] = foods[(pageId - 1) * pageSize + i];
				images[i] = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
			}
		} else if (loadType == LOADTYPE_KEY) {
			TextView textView1 = (TextView) findViewById(R.id.textView1);
			textView1.setText(pageId + "/" + pageCount);
			int leftCount = searchArray.size() - ((pageId - 1) * pageSize);
			int pageCount = leftCount > (pageSize-1)?pageSize:leftCount;
			titles = new String[pageCount];
			images = new Bitmap[pageCount];
			for (int i = 0; i < pageCount; i++) {
				titles[i] = searchArray.get((pageId - 1) * pageSize + i);
				images[i] = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
			}
		}
		new AsyncGetIcon().execute(new String[] {});
		ProgressBar progress = (ProgressBar) FoodMenuActivity.this.findViewById(R.id.progress_foodmenu);
		progress.setVisibility(View.VISIBLE);
	}

	public class ImageAdapter extends BaseAdapter {
		private Context context;

		public ImageAdapter(Context c) {
			context = c;
		}

		//---returns the number of images---
		public int getCount() {
			return images.length;
		}

		//---returns the ID of an item--- 
		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		//---returns an ImageView view---
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView icon;
			icon = new ImageView(context);

			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View row = inflater.inflate(R.layout.row, parent, false);
			TextView label = (TextView) row.findViewById(R.id.image_name);
			label.setText(titles[position]);
			icon = (ImageView) row.findViewById(R.id.album_image);

			icon.setImageBitmap(images[position]);

			return row;
		}

	}

	class AsyncGetIcon extends AsyncTask<String, Integer, Object> {

		@Override
		protected Object doInBackground(String... params) {
			try {
				images = Util.getBitmapImageIcon(titles);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Object result) {
			if (Boolean.valueOf(result.toString())) {
				ProgressBar progress = (ProgressBar) FoodMenuActivity.this.findViewById(R.id.progress_foodmenu);
				progress.setVisibility(View.INVISIBLE);
				gridView.invalidateViews();
			}
		}
	}
}
